﻿(function ($) {
    $.fn.extend({
        ggrid: function (options) {

            var defaults = {
                url: document.href,
                dataType: 'json',
                columns: [],
                actions: [],
                defaultSort: "",
                defaultSortOrder: "asc",
                usePaging: true,
                pageSize: 10,
                width: 'auto',
                height: 'auto'
            }

            var options = $.extend(defaults, options);

            return this.each(function () {
                var o = options;
                var obj = $(this);

                ggrid_init(obj, options);
                ggrid_load(obj, options);
            });
        }
    });
})(jQuery);


function ggrid_init(obj, options) {
    var id = obj.attr("id");
    var html = "";

    html += "<input type='text' id='ggrid_s_" + id + "' class='ggrid_search' />";
    html += "<input type='button' id='ggrid_sb_" + id + "' value='search' class='ggrid_search_btn' />";

    html += "<table id=ggrid_tbl_" + id + " class='ggrid_table'><thead><tr>"

    for (var i in options.columns) {
        var col = options.columns[i];
        html += "<th sort='" + col.name + "' class='ggrid_th'>" + col.display + "</th>";
    }
    if (options.actions.length > 0) {
        html += "<th class='ggrid_th'></th>";
    }
    html += "</tr></thead><tbody></<tbody></table>"

    html += "<table id='ggrid_pa_" + id + "' class='ggrid_pager_table'><tr><td class='ggrid_pager_left'>";
    html += "Rows: ";
    html += "<span id='ggrid_sr_" + id + "'>X</span>";
    html += " - ";
    html += "<span id='ggrid_lr_" + id + "'>X</span>";
    html += " of ";
    html += "<span id='ggrid_t_" + id + "'>X</span>";
    html += "</td><td class='ggrid_pager_center'>";
    html += "<span id='ggrid_prh_" + id + "'>";
    html += "<a id='ggrid_pr_" + id + "' href='#'><img src='/Content/Images/previous.png' /></a>";
    html += "</span>";
    html += "<span id='ggrid_nh_" + id + "'>&nbsp;&nbsp;";
    html += "<a id='ggrid_n_" + id + "' href='#'><img src='/Content/Images/next.png' /></a>";
    html += "</span>";
    html += "</td><td class='ggrid_pager_right'>";
    html += "<span id='ggrid_ph_" + id + "'>";
    html += "Page: ";
    html += "<input type='text' id='ggrid_p_" + id + "' value='1' size='1' />";
    html += "</span>";
    html += " Size: ";
    html += "<select id='ggrid_ps_" + id + "'>";
    html += "<option value='10'>10</option>"
    html += "<option value='25'>25</option>"
    html += "<option value='50'>50</option>"
    html += "<option value='100'>100</option>"
    html += "<option value='250'>250</option>"
    html += "<option value='500'>500</option>"
    html += "</select>";

    html += "</td></tr></table>";
    html += "<span id='ggrid_none_" + id + "' class='ggrid_none'>No records found!</span>";

    obj.html(html);

    var table = $("#ggrid_tbl_" + id);
    var search = $("#ggrid_s_" + id);
    var searchbutton = $("#ggrid_sb_" + id);
    var pager = $("#ggrid_pa_" + id);
    var startrow = $("#ggrid_sr_" + id);
    var lastrow = $("#ggrid_lr_" + id);
    var totalrows = $("#ggrid_t_" + id);
    var nextholder = $("#ggrid_nh_" + id);
    var next = $("#ggrid_n_" + id);
    var previousholder = $("#ggrid_prh_" + id);
    var previous = $("#ggrid_pr_" + id);
    var pageholder = $("#ggrid_ph_" + id);
    var page = $("#ggrid_p_" + id);
    var pagesize = $("#ggrid_ps_" + id);
    var none = $("#ggrid_none_" + id);

    none.hide();
    pagesize.val(10);

    $("th", table).each(function () {
        $(this).click(function () {
            var sort = $(this).attr('sort');
            var dir = $(this).attr('dir');
            dir = (dir ? (dir == "asc" ? "desc" : "asc") : 'asc');
            $(this).attr('dir', dir);
            $(this).parent().children().removeClass("ggrid_th_asc ggrid_th_desc");
            $(this).addClass("ggrid_th_" + dir);
            page.val(1);
            ggrid_load(obj, options, sort, dir);
        });
    });

    search.keypress(function (event) {
        if (event.which == '13') {
            page.val("1");
            ggrid_load(obj, options);
        }
    });

    searchbutton.click(function () {
        page.val("1");
        ggrid_load(obj, options);
    });

    previous.click(function () {
        page.val(parseInt(page.val()) - 1);
        ggrid_load(obj, options);
    });

    next.click(function () {
        page.val(parseInt(page.val()) + 1);
        ggrid_load(obj, options);
    });

    page.change(function () {
        var newindex = ggrid_cleanpage(obj);
        page.val(newindex);
        ggrid_load(obj, options);
    });

    pagesize.change(function () {
        page.val("1");
        ggrid_load(obj, options);
    });
}

function ggrid_load(obj, options, sort, dir) {

    var id = obj.attr("id");
    var table = $("#ggrid_tbl_" + id);
    var search = $("#ggrid_s_" + id);
    var searchbutton = $("#ggrid_sb_" + id);
    var pager = $("#ggrid_pa_" + id);
    var startrow = $("#ggrid_sr_" + id);
    var lastrow = $("#ggrid_lr_" + id);
    var totalrows = $("#ggrid_t_" + id);
    var nextholder = $("#ggrid_nh_" + id);
    var next = $("#ggrid_n_" + id);
    var previousholder = $("#ggrid_prh_" + id);
    var previous = $("#ggrid_pr_" + id);
    var pageholder = $("#ggrid_ph_" + id);
    var page = $("#ggrid_p_" + id);
    var pagesize = $("#ggrid_ps_" + id);
    var none = $("#ggrid_none_" + id);

    var p = parseInt(page.val());
    var ps = parseInt(pagesize.val());
    var sr = (p * ps) - ps;

    var input = {
        StartRow: sr,
        PageSize: pagesize.val(),
        Sort: sort ? sort : options.defaultSort,
        SortDirection: dir ? dir : options.defaultSortOrder,
        Search: search.val()
    };

    $("tbody", table).fadeOut(100);
    none.fadeOut(100);

    Ajax({
        url: options.url,
        data: JSON.stringify(input),
        success: function (data) {
            ggrid_bind(obj, data, options);
        }
    });
}

function ggrid_bind(obj, data, options) {

    var id = obj.attr("id");
    var table = $("#ggrid_tbl_" + id);
    var search = $("#ggrid_s_" + id);
    var searchbutton = $("#ggrid_sb_" + id);
    var pager = $("#ggrid_pa_" + id);
    var startrow = $("#ggrid_sr_" + id);
    var lastrow = $("#ggrid_lr_" + id);
    var totalrows = $("#ggrid_t_" + id);
    var nextholder = $("#ggrid_nh_" + id);
    var next = $("#ggrid_n_" + id);
    var previousholder = $("#ggrid_prh_" + id);
    var previous = $("#ggrid_pr_" + id);
    var pageholder = $("#ggrid_ph_" + id);
    var page = $("#ggrid_p_" + id);
    var pagesize = $("#ggrid_ps_" + id);
    var none = $("#ggrid_none_" + id);

    var html = "";

    $("tbody", table).empty();

    for (var i in data.Records) {
        html += "<tr>";
        for (var j in options.columns) {
            val = eval("data.Records[i]." + options.columns[j].name);
            if (options.columns[j].formatFunction) {
                val = options.columns[j].formatFunction(val);
            }             
            html += "<td>";
            html += val;
            html += "</td>"
        }
        if (options.actions.length > 0) {
            html += "<td>";
            for (var j in options.actions) {
                var a = options.actions[j];
                html += "<a href='";
                if (a.showConfirm) {
                    html += "javascript:if (confirm(\"are you sure?\")) {location.href = \"";
                    html += a.action.replace("{0}", data.Records[i][a.idColumn])
                    html += "\"; }";
                } else {
                    html += a.action.replace("{0}", data.Records[i][a.idColumn]);
                }
                html += "'><img src='";
                html += a.image;
                html += "' /></a>";
            }
            html += "</td>"
        }
        html += "</tr>"
    }

    $("tbody", table).html(html);
    $('tbody tr:even', table).addClass("alt-row");

    var ipagesize = parseInt(pagesize.val())
    var itotal = parseInt(data.TotalRecords);
    var igoto = parseInt(page.val());
    var istart = ((igoto - 1) * ipagesize);
    var iend = ((istart + ipagesize) > itotal ? itotal : (istart + ipagesize));
    istart = data.TotalRecords == 0 ? 0 : istart + 1;

    page.val(igoto);
    startrow.html(istart);
    lastrow.html(iend);
    totalrows.html(itotal);

    var pagecount = Math.floor(itotal / ipagesize) + (itotal % ipagesize > 0 ? 1 : 0);

    if (pagecount > 1) {
        pageholder.show();
        page.removeAttr('disabled');
    } else {
        pageholder.hide();
        page.attr('disabled', true);
    }

    if (igoto != pagecount) {
        nextholder.show();
    } else {
        nextholder.hide();
    }

    if (igoto != 1) {
        previousholder.show();
    } else {
        previousholder.hide();
    }

    if (search.val().length > 0) {
        var arr = search.val().split(' ');
        $("tbody td", table).each(function () {
            var t = $(this).text();
            for (var i in arr) {
                t = ggrid_highlight(arr[i], t);
            }
            $(this).html(t);
        });
    }

    if (itotal != 0) {
        pager.show();
        table.show();
        none.hide();
        $("tbody", table).fadeIn(200);
    } else {
        pager.hide();
        table.hide();
        none.fadeIn(200); ;
    }
}

function ggrid_cleanpage(obj) {
    var id = obj.attr("id");
    var totalrows = $("#ggrid_t_" + id);
    var page = $("#ggrid_p_" + id);
    var pagesize = $("#ggrid_ps_" + id);

    var newindex = parseInt(page.val());

    if (ggrid_isNumeric(newindex)) {
        newindex = (newindex == 0 ? newindex + 1 : newindex);
        var ipagesize = parseInt(pagesize.val())
        var itotal = parseInt(totalrows.text());
        var pagecount = Math.floor(itotal / ipagesize) + (itotal % ipagesize > 0 ? 1 : 0);
        newindex = (newindex > pagecount ? pagecount : newindex);
    } else {
        newindex = 1;
    }

    return newindex;
}

function ggrid_isNumeric(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

function ggrid_highlight(word, text) {
    var rgxp = new RegExp(word, 'g');
    var repl = '<span style="background-color:yellow";>' + word + '</span>';
    text = text.replace(rgxp, repl);
    return text;
}